package com.example.rocketmqdemo.transaction.domain.transactionexecutor;

import com.alibaba.cola.exception.SysException;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

@Slf4j
public class DefaultLocalTransactionExecutor<R> implements LocalTransactionExecutor<R> {

    private final Supplier<R> supplier;
    private Throwable throwable;
    private R result;

    public DefaultLocalTransactionExecutor(Supplier<R> supplier) {
        this.supplier = supplier;
    }

    @Override
    public void execute(Object txId, Object message) {
        try {
            result = supplier.get();
        } catch (Throwable e) {
            throwable = e;
        }
    }

    @Override
    public R getResult() {
        if (null != throwable) {
            if (throwable instanceof SysException) {
                throw (SysException) throwable;
            }
            throw new SysException(throwable.getMessage(), throwable);
        }
        return result;
    }

    @Override
    public void addLocalTransactionRecord(Runnable runnable) {
        try {
            runnable.run();
        } catch (Throwable e) {
            throwable = e;
            throw e;
        }
    }
}
